package com.ruoyi.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.SysConfigConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.system.domain.JiajiaMappoints;
import com.ruoyi.system.domain.JiajiaProxyApplication;
import com.ruoyi.system.domain.JiajiaTransferAccounts;
import com.ruoyi.system.domain.JiajiaUser;
import com.ruoyi.system.mapper.JiajiaMappointsMapper;
import com.ruoyi.system.mapper.JiajiaProxyApplicationMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.IJiajiaProxyApplicationService;
import com.ruoyi.system.service.IJiajiaTransferAccountsService;
import com.ruoyi.system.service.IJiajiaUserService;
import com.ruoyi.system.utils.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

/**
 * 代理申请记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-04
 */
@Service
public class JiajiaProxyApplicationServiceImpl implements IJiajiaProxyApplicationService
{

    private static final Logger logger = LoggerFactory.getLogger(JiajiaProxyApplicationServiceImpl.class);

    @Autowired
    private IJiajiaTransferAccountsService jiajiaTransferAccountsService;

    @Autowired
    private JiajiaProxyApplicationMapper jiajiaProxyApplicationMapper;

    @Autowired
    private IJiajiaUserService  userService;

    @Resource
    private SysDeptMapper sysDeptMapper;

    @Resource
    private JiajiaMappointsMapper jiajiaMappointsMapper;

    /**
     * 查询代理申请记录
     *
     * @param id 代理申请记录主键
     * @return 代理申请记录
     */
    @Override
    public JiajiaProxyApplication selectJiajiaProxyApplicationById(Long id) {
        return jiajiaProxyApplicationMapper.selectJiajiaProxyApplicationById(id);
    }

    /**
     * 查询代理申请记录列表
     *
     * @param jiajiaProxyApplication 代理申请记录
     * @return 代理申请记录
     */
    @Override
    public List<JiajiaProxyApplication> selectJiajiaProxyApplicationList(JiajiaProxyApplication jiajiaProxyApplication) {
        return jiajiaProxyApplicationMapper.selectJiajiaProxyApplicationList(jiajiaProxyApplication);
    }

    /**
     * 新增代理申请记录
     *
     * @param jiajiaProxyApplication 代理申请记录
     * @return 结果
     */
    @Override
    public Long insertJiajiaProxyApplication(JiajiaProxyApplication jiajiaProxyApplication) {
        JiajiaProxyApplication proxyApplication = new JiajiaProxyApplication();
        proxyApplication.setUserId(TokenUtil.getUid());
        jiajiaProxyApplication.setUserId(TokenUtil.getUid());
        List<JiajiaProxyApplication> jiajiaProxyApplications = jiajiaProxyApplicationMapper.selectJiajiaProxyApplicationList(proxyApplication);
        if(ObjectUtil.isNotEmpty(jiajiaProxyApplications)){
 //            JiajiaProxyApplication jiajiaProxyApplication1 = jiajiaProxyApplications.stream().filter(a -> Optional.ofNullable(a.getTransactionId()).isPresent()).findFirst().orElse(null);
//            if(Optional.ofNullable(jiajiaProxyApplication1).isPresent()){
//                throw new ServiceException("请误重复申请");
//            }else{
//                return jiajiaProxyApplications.get(0).getId();
//
//            }
            for (JiajiaProxyApplication application : jiajiaProxyApplications){
                if (jiajiaProxyApplication.getType().equals(0)||jiajiaProxyApplication.getType()==0){
                    if ((application.getType().equals(0)||application.getType()==0)&&(application.getStatus().equals(1)||application.getStatus()==1)){
                        throw new ServiceException("请勿重复申请");
                    }
                }
            }
        }
        if(jiajiaProxyApplication.getType().equals("2")){
            JiajiaProxyApplication presentedApplication = new JiajiaProxyApplication();
            presentedApplication.setCommunity(jiajiaProxyApplication.getCommunity());
            presentedApplication.setType(jiajiaProxyApplication.getType());
            List<JiajiaProxyApplication> presentedServices =  jiajiaProxyApplicationMapper.selectJiajiaProxyApplicationList(presentedApplication);
            if (ObjectUtil.isNotEmpty(presentedServices)){
                throw new RuntimeException("该小区已有代理");
            }
        }
        jiajiaProxyApplication.setPaymentChannels(TokenUtil.getPlatForms());
        jiajiaProxyApplication.setCreateTime(new Date());
        jiajiaProxyApplicationMapper.insertJiajiaProxyApplication(jiajiaProxyApplication);
        return jiajiaProxyApplication.getId();
    }


    /**
     * 修改代理申请记录
     *
     * @param jiajiaProxyApplication 代理申请记录
     * @return 结果
     */
    @Override
    public int updateJiajiaProxyApplication(JiajiaProxyApplication jiajiaProxyApplication) {
        return jiajiaProxyApplicationMapper.updateJiajiaProxyApplication(jiajiaProxyApplication);
    }

    /**
     * 批量删除代理申请记录
     *
     * @param ids 需要删除的代理申请记录主键
     * @return 结果
     */
    @Override
    public int deleteJiajiaProxyApplicationByIds(String ids) {
        return jiajiaProxyApplicationMapper.deleteJiajiaProxyApplicationByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除代理申请记录信息
     *
     * @param id 代理申请记录主键
     * @return 结果
     */
    @Override
    public int deleteJiajiaProxyApplicationById(Long id) {
        return jiajiaProxyApplicationMapper.deleteJiajiaProxyApplicationById(id);
    }

    /**
     * 从地址字符串中截取区县信息
     *
     * @param address 地址字符串
     * @return 区县信息
     */
    public String extractDistrict(String address) {
        int districtIndex = address.indexOf("区");
        if(districtIndex<0){
            districtIndex = address.indexOf("县");
        }
        int cityIndex = address.indexOf("市");
        if (districtIndex != -1) {
            String district =address.substring(0, districtIndex + 1);
            district=district.substring(cityIndex+1,district.length());
            // 从字符串开头到“区”字的位置截取区县信息
            return district;
        }
        return "";
    }

    @Override
    public int auditJiajiaProxyApplication(JiajiaProxyApplication jiajiaProxyApplication) {
        if (jiajiaProxyApplication.getStatus()==1){
            JiajiaProxyApplication  proxyApplication= jiajiaProxyApplicationMapper.selectJiajiaProxyApplicationById(jiajiaProxyApplication.getId());
            JiajiaUser jiajiaUser = userService.selectJiajiaUserById(proxyApplication.getUserId());
             if(proxyApplication.getType() ==2){
                //小区代理
                // 小区加入的dept表
                 //判断订单归属区域
                 String adcodeBylatlon = TokenUtil.getAdcodeBylatlon(proxyApplication.getLatitude(), proxyApplication.getLongitude());
                 SysDept dept = sysDeptMapper.selectDeptByAdcode(adcodeBylatlon);
                 if(!Optional.ofNullable(dept).isPresent()) {
                     throw new ServiceException("暂未开放该行政区域，如有需要，请联系客服！");
                 }

                SysDept parentDept = new SysDept();
                parentDept.setParentId(dept.getDeptId());
                parentDept.setDeptName(proxyApplication.getCommunity());
                parentDept.setAncestors(dept.getAncestors()+","+dept.getDeptId());
                parentDept.setLeader(proxyApplication.getName());
                parentDept.setPhone(proxyApplication.getPhone());
                parentDept.setUserId(proxyApplication.getUserId());
                 parentDept.setDistrict("5");
                sysDeptMapper.insertDept(parentDept);
                //关联区域信息
                JiajiaMappoints jiajiaMappoints=new JiajiaMappoints();
                jiajiaMappoints.setProxyId(jiajiaProxyApplication.getId());
                jiajiaMappoints.setUserId(jiajiaProxyApplication.getUserId());
                List<JiajiaMappoints> jiajiaMappoints1 = jiajiaMappointsMapper.selectJiajiaMappointsList(jiajiaMappoints);
                jiajiaMappoints1.stream().forEach(a->{
                    a.setDeptId(parentDept.getDeptId());
                    jiajiaMappointsMapper.updateJiajiaMappoints(a);
                });
                //关联user表
                jiajiaUser.setDeptId(parentDept.getDeptId());
                 userService.updateJiajiaUser(jiajiaUser);
                //审核通过后进入钱包
                 //收益人
                 JiajiaUser jiajiaUser1 = userService.selectBeneficiary(jiajiaUser);
                 BigDecimal money = jiajiaUser1.getMoney();
                 logger.info("money:"+money);
                 String income = CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY + SysConfigConstants.sys_promotion_community_agent).toString();
                 logger.info("income:"+income);

                 BigDecimal incomeAfter = money.add(new BigDecimal(income));
                 logger.info("incomeAfter:"+incomeAfter);

                 jiajiaUser1.setMoney(incomeAfter);
                 userService.updateJiajiaUser(jiajiaUser1);
                 //加入流水表
                 JiajiaTransferAccounts jiajiaTransferAccounts=new JiajiaTransferAccounts();
                 jiajiaTransferAccounts.setUserId(jiajiaUser1.getId());
                 jiajiaTransferAccounts.setTransferAmount(new BigDecimal(income));
                 jiajiaTransferAccounts.setOrderId(jiajiaProxyApplication.getId());
                 jiajiaTransferAccounts.setSourceUserId(jiajiaUser.getId());
                 jiajiaTransferAccounts.setOrderType("1");
                 jiajiaTransferAccounts.setTransferType("3");
                 jiajiaTransferAccounts.setRemark("推广小区收益");
                 jiajiaTransferAccounts.setVersion(LocalDateTime.now()+String.valueOf(Math.random()));
                 jiajiaTransferAccounts.setDeleted("1");
                 jiajiaTransferAccountsService.insertJiajiaTransferAccounts(jiajiaTransferAccounts);
            }
        }


        return jiajiaProxyApplicationMapper.updateJiajiaProxyApplication(jiajiaProxyApplication);
    }

    @Override
    public List<JiajiaProxyApplication> selectItSMine(Integer status) {
        JiajiaProxyApplication proxyApplication=new JiajiaProxyApplication();
        proxyApplication.setStatus(status);
        proxyApplication.setUserId(TokenUtil.getUid());
        List<JiajiaProxyApplication> jiajiaProxyApplication =jiajiaProxyApplicationMapper.selectJiajiaProxyApplicationList(proxyApplication);
        return jiajiaProxyApplication;
    }

    @Override
    public void examine(JiajiaProxyApplication jiajiaProxyApplication) {
        JiajiaProxyApplication jjpa = jiajiaProxyApplicationMapper.selectJiajiaProxyApplicationById(jiajiaProxyApplication.getId());
        jjpa.setExamine("1");
        jiajiaProxyApplicationMapper.updateJiajiaProxyApplication(jjpa);
        JSONArray objects = JSONArray.parseArray(jiajiaProxyApplication.getLatlong());
        Iterator<Object> iterator = objects.iterator();
        while (iterator.hasNext()){
            JiajiaMappoints jiajiaMappoints=new JiajiaMappoints();
            Object next = iterator.next();
            JSONObject jObject = JSONObject.parseObject(next.toString());
            jiajiaMappoints.setProxyId(jjpa.getId());
            jiajiaMappoints.setUserId(jjpa.getUserId());
            jiajiaMappoints.setLatitude(jObject.getString("lat"));
            jiajiaMappoints.setLongitude( jObject.getString("lng"));
            jiajiaMappointsMapper.insertJiajiaMappoints(jiajiaMappoints);
        }
    }

    @Override
    public List<JiajiaProxyApplication> selectByUserId(Long id) {
        List<JiajiaProxyApplication> jiajiaProxyApplication =jiajiaProxyApplicationMapper.selectByUserId(id);
        return jiajiaProxyApplication;
    }
}
